package com.fancon.android.gardenjokesx.activity;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.WebView;

import com.fancon.android.activity.FanconBaseActivity;
import com.fancon.android.cache.utils.StorageUtils;
import com.fancon.android.gardenjokesx.R;
import com.fancon.android.gardenjokesx.utils.Constant;
import com.fancon.android.multithread.RequestUI;
import com.fancon.android.ui.widget.FanconProgressBar;

public class PhotoDetailActivity extends FanconBaseActivity {
	private String photoUrl = Constant.XCOMIC_ICON_ASSET;
	private WebView mWb;

	private String imagePath;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		try {
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			setContentView(R.layout.photo_detail);
			mWb = (WebView) findViewById(R.id.rage_detail);
			Bundle extras = getIntent().getExtras();
			mWb.getSettings().setBuiltInZoomControls(true);
			// mWb.getSettings().setUseWideViewPort(true);
			try {
				if (extras != null) {
					photoUrl = extras.getString("photoUrl");
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			loadImage();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	private void loadImage() {
		try {
			if (photoUrl != null) {
				String filename = String.valueOf(photoUrl.hashCode());
				//String base = Environment.getExternalStorageDirectory()
				//		.getAbsolutePath().toString();
				File file = new File(StorageUtils.getIndividualCacheDirectory(
						getApplicationContext()).getAbsolutePath()
						+ "/" + filename);
				if (file.exists()) {
					imagePath = StorageUtils.getIndividualCacheDirectory(
							getApplicationContext()).getAbsolutePath()
							+ "/" + filename;
					String html = "<html><head></head><body><center><img src=\""
							+ "file:/"
							+ imagePath
							+ "\"></center></body></html>";
					mWb.loadDataWithBaseURL("", html, "text/html", "utf-8", "");
				} else {
					DownloadPhotoRequest allRageRequest = new DownloadPhotoRequest(
							"downloadphoto", this, photoUrl);
					getGlobalState().getRequestQueue().addRequest(
							allRageRequest);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
		}
	}

	class DownloadPhotoRequest extends RequestUI {
		private String photoUrl;
		private FanconProgressBar progress;
		private Context mContext;

		public DownloadPhotoRequest(Object key, Activity activity,
				String photoUrl) {
			super(key, activity);
			// TODO Auto-generated constructor stub
			mContext = activity;
			this.photoUrl = photoUrl;
			progress = FanconProgressBar.show(mContext, "");
		}

		@Override
		public void execute() throws Exception {
			// TODO Auto-generated method stub
			downloadFromUrl(photoUrl, String.valueOf(photoUrl.hashCode()));
		}

		@Override
		public void executeUI(Exception ex) {
			// TODO Auto-generated method stub
			try {
				if (progress != null) {
					progress.dismiss();
				}
				String filename = String.valueOf(photoUrl.hashCode());
				File file = new File(StorageUtils.getIndividualCacheDirectory(
						getApplicationContext()).getAbsolutePath()
						+ "/" + filename);
				if (file.exists()) {
					imagePath = StorageUtils.getIndividualCacheDirectory(
							getApplicationContext()).getAbsolutePath()
							+ "/" + filename;
					String html = "<html><head></head><body><center><img src=\""
							+ "file:/"
							+ imagePath
							+ "\"></center></body></html>";
					mWb.loadDataWithBaseURL("", html, "text/html", "utf-8", "");
				}
			} catch (Exception e) {
				e.printStackTrace();
				// TODO: handle exception
			}
		}

		public void downloadFromUrl(String DownloadUrl, String fileName) {

			try {
				File dir = StorageUtils
						.getIndividualCacheDirectory(getApplicationContext());
				if (dir.exists() == false) {
					dir.mkdirs();
				}

				URL url = new URL(DownloadUrl); // you can write here any link
				File file = new File(dir, fileName);

				long startTime = System.currentTimeMillis();

				/* Open a connection to that URL. */
				URLConnection ucon = url.openConnection();

				/*
				 * Define InputStreams to read from the URLConnection.
				 */
				InputStream is = ucon.getInputStream();
				BufferedInputStream bis = new BufferedInputStream(is);

				/*
				 * Read bytes to the Buffer until there is nothing more to
				 * read(-1).
				 */
				ByteArrayBuffer baf = new ByteArrayBuffer(50);
				int current = 0;
				while ((current = bis.read()) != -1) {
					baf.append((byte) current);
				}

				/* Convert the Bytes read to a String. */
				FileOutputStream fos = new FileOutputStream(file);
				fos.write(baf.toByteArray());
				fos.flush();
				fos.close();
				Log.d("DownloadManager",
						"download ready in "
								+ ((System.currentTimeMillis() - startTime) / 1000)
								+ " sec");

			} catch (IOException e) {
				Log.d("DownloadManager", "Error: " + e);
			}

		}

	}
}
